package org.yinweichen.llm_dataset_backend.util;

import org.yinweichen.llm_dataset_backend.repository.*;
import org.springframework.stereotype.Component;
import org.yinweichen.llm_dataset_backend.service.StandardQuestionService;

import java.util.Random;

@Component
public final class IdGenerator {
//    private static final int ID_LENGTH = 8;
    private static final Random random = new Random();

    private final OriginalQuestionRepository originalQuestionRepository;
    private final StandardQuestionRepository standardQuestionRepository;
    private final OriginalAnswerRepository originalAnswerRepository;
    private final CandidateAnswerRepository candidateAnswerRepository;


    public IdGenerator(OriginalQuestionRepository originalQuestionRepository,
                       StandardQuestionRepository standardQuestionRepository,
                       OriginalAnswerRepository originalAnswerRepository,
                       CandidateAnswerRepository candidateAnswerRepository) {
        this.originalQuestionRepository = originalQuestionRepository;
        this.standardQuestionRepository = standardQuestionRepository;
        this.originalAnswerRepository = originalAnswerRepository;
        this.candidateAnswerRepository = candidateAnswerRepository;
    }

    public Long generateCandidateAnswerId() {
        Long id;
        do {
            id = generateRandomId(10);
        } while (candidateAnswerRepository.existsById(id));
        return id;
    }

    public Long generateUniqueIdForOriginalQuestion() {
        Long id;
        do {
            id = generateRandomId(8);
        } while (originalQuestionRepository.existsById(id));
        return id;
    }
    public Long generateUniqueIdForStandardQuestion() {
        Long id;
        do {
            id = generateRandomId(9);
        } while (standardQuestionRepository.existsById(id));
        return id;
    }
//    public Long generateUniqueIdForStandardAnswer() {
//        Long id;
//        do {
//            id = generateRandomId(9);
//        } while (standardAnswerRepository.existsById(id));
//        return id;
//    }
    public Long generateUniqueIdForOriginalAnswer() {
        Long id;
        do {
            id = generateRandomId(10);
        } while (originalAnswerRepository.existsById(id));
        return id;
    }

    private Long generateRandomId(int length) {
        long min = (long) Math.pow(10, length - 1);
        long max = (long) Math.pow(10, length) - 1;
        return min + ((long) (random.nextDouble() * (max - min)));
    }
}
